const axios = require('axios');

axios.interceptors.request.use(
    config => {
        config.headers['User-Agent'] = `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36 Edg/117.0.2045.43`;
        // 'Connection': 'keep-alive'
        config.headers['Connection'] = `keep-alive`;
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);
const requestGet = async function (href, map) {
    try {
        href = encodeURI(href);
        const res = await axios.get(href, { headers: map })
        if (res.status == 200) {
            return res.data;
        }
        console.log(res.toString());
        return { code: res.status, error: res.statusText };
    } catch (error) {
        if (error && error.response && error.response.data) {
            return { code: 4041, error: error.response.data };
        }
        return { code: 4042, error: error.message ? error.message : `${error}` };
    }
}
const requestPost = async function (href, data, map) {
    href = encodeURI(href);
    console.log(href);
    const res = await axios.post(href, data, { headers: map })
    if (res.status == 200) {
        return res.data;
    }
    return { code: res.status, error: res.statusText };
}

/**
 * 加载搜索 href
 * @param {string} tag 
 * @param {string} filter 
 */
function loadSearchHref(tag, filter) {
    const jsfile = require('../search/' + tag);
    if (jsfile && jsfile['searchHref']) {
        return jsfile['searchHref'](filter);
    }
    return undefined;
}

module.exports = { requestGet, requestPost, loadSearchHref, axios }